#pragma once
#include <iostream>
#include <strings.h>
#include <cstring>
#include <string>
#include <cerrno>
#include <sys/types.h>
#include <sys/socket.h>
#include <strings.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <functional>
#include <pthread.h>
#include "nocopy.hpp"
#include "Comm.hpp"
#include "Log.hpp"
#include "lnetAddr.hpp"
#include "ThreadPool.hpp"

static const std::string defaultip = "0.0.0.0";
static const uint16_t defaultport = 8888;
const static int defaultfd = -1;
const static int defaultsize = 1024;

//using cb_t = std::function<std::string(std::string)>;//定义了一个类型，返回值和参数都是string

using task_t = std::function<void ()>;

/// 无ip版本


class UdpServer:public nocopy
{
public:
     // UdpServer(cb_t OnMessage, uint16_t port = defaultport)
     // :_port(port), _sockfd(defaultfd), _OnMessage(OnMessage)
     // {}
     UdpServer(uint16_t port = defaultport): _port(port), _sockfd(defaultfd)
    {
        pthread_mutex_init(&_user_mutex, nullptr);
    }


     void Init()
     {
          //1.创建socket, 就是创建了文件细节
          _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
          if(_sockfd < 0)
          {
               lg.LogMessage(Fatal, "socket errr, %d : %s\n", errno, strerror(errno));
               exit(Socket_Err);
          }

          lg.LogMessage(Info, "socket success, sockfd: %d\n", _sockfd);

          //2.绑定，指定网络信息
          struct sockaddr_in local;
          bzero(&local, sizeof(local));//memset指定大小全部清零//头文件strings.h
          local.sin_family = AF_INET;//使用ipv4地址
          local.sin_port = htons(_port);//htons是主机转网络

          local.sin_addr.s_addr = INADDR_ANY;//0,ip地址设为零  本地任意ip绑定的方式
          //local.sin_addr.s_addr = inet_addr(_ip.c_str());//1.将字符串风格的地址变4字节 2.变成网络序列
          
          //结构体填完，并未设置到内核中，还在栈中


          int n = bind(_sockfd, (struct sockaddr*)&local, sizeof(local));
          if(n != 0)
          {
               lg.LogMessage(Fatal, "bind errr, %d : %s\n", errno, strerror(errno));
               exit(Bind_Err);
          }

          ThreadPool<task_t>::GetInstance()->Start();//创建线程池

     }

     void AddOnlineUser(InetAddr addr)//添加在线用户
    {
        LockGuard lockguard(&_user_mutex);
        for(auto &user : _online_user)
        {
            if(addr == user) return;
        }
        _online_user.push_back(addr);
        lg.LogMessage(Debug, "%s:%d is add to onlineuser list...\n", addr.Ip().c_str(), addr.Port());
    }

    void Route(int sock, const std::string &message)//路由
    {
        LockGuard lockguard(&_user_mutex);
        for(auto &user : _online_user)//广播式的发给所有人
        {
            sendto(sock, message.c_str(), message.size(), 0, (struct sockaddr*)&user.GetAddr(), sizeof(user.GetAddr()));
            lg.LogMessage(Debug, "server send message to %s:%d, message: %s\n", user.Ip().c_str(), user.Port(), message.c_str());
        }
    }

     void Start()
     {
          //服务器永远不退出
          char buffer[defaultsize];
          for(;;)
          {
               struct sockaddr_in peer;
               socklen_t len = sizeof(peer);
               ssize_t n = recvfrom(_sockfd, buffer, sizeof(buffer)-1, 0, (struct sockaddr *)&peer, &len);
               if(n > 0)
               {
                    // 用户信息
                    InetAddr addr(peer);
                    AddOnlineUser(addr);
                    buffer[n] = 0;
                    std::string message = "[";
                    message += addr.Ip();
                    message += ":";
                    message += std::to_string(addr.Port());
                    message += "]# ";
                    message += buffer;
                    auto task = std::bind(&UdpServer::Route, this, _sockfd, message);
                    ThreadPool<task_t>::GetInstance()->Push(task);//类中放的是函数对象
                     

                    //处理消息，由该回调函数处理
                    // std::string response = _OnMessage(buffer);

                    //std::cout << "[" << addr.PrintDebug() << "]# " << buffer << std::endl;
                    //sendto(_sockfd, buffer, strlen(buffer), 0, (struct sockaddr *)&peer, len);
                    // sendto(_sockfd, response.c_str(), response.size(), 0, (struct sockaddr *)&peer, len);
                    // buffer[n] = 0;
                    // std::cout << "client say# " << buffer << std::endl;
                    // //向客户端发送
                    // sendto(_sockfd, buffer, strlen(buffer), 0, (struct sockaddr *)&peer, len);
               }
          }
          


     }

     ~UdpServer(){
           pthread_mutex_destroy(&_user_mutex);
     }

private:
     // std::string _ip;//后面需要调整//动态绑定后不需要该ip地址
     uint16_t _port;
     int _sockfd;
     std::vector<InetAddr> _online_user;//会被多个线程同时访问,模拟在线用户列表
     pthread_mutex_t _user_mutex;
     //cb_t _OnMessage; //回调

};